#include "LinearEquationWindow.h"
#include "RenderWidget.h"
#include <Eigen>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLabel>
#include <QMessageBox>

LinearEquationWindow::LinearEquationWindow(QWidget *parent)
    : QWidget(parent)
    , render_(new RenderWidget(this))
{
    setupUi();
}

//ui设计
void LinearEquationWindow::setupUi() {
    auto *mainLay = new QHBoxLayout(this);

    // 左侧：控制面板
    ctrlGroup_ = new QGroupBox(tr("线性方程组 Ax = b"), this);
    ctrlGroup_->setMaximumWidth(240);
    auto *vLay = new QVBoxLayout(ctrlGroup_);

    // 系数矩阵输入
    vLay->addWidget(new QLabel(tr("A11, A12:"), ctrlGroup_));
    leA11_ = new QLineEdit(ctrlGroup_);
    leA12_ = new QLineEdit(ctrlGroup_);
    vLay->addWidget(leA11_);
    vLay->addWidget(leA12_);

    vLay->addSpacing(5);
    vLay->addWidget(new QLabel(tr("A21, A22:"), ctrlGroup_));
    leA21_ = new QLineEdit(ctrlGroup_);
    leA22_ = new QLineEdit(ctrlGroup_);
    vLay->addWidget(leA21_);
    vLay->addWidget(leA22_);

    // 常数向量输入
    vLay->addSpacing(10);
    vLay->addWidget(new QLabel(tr("b1, b2:"), ctrlGroup_));
    leB1_ = new QLineEdit(ctrlGroup_);
    leB2_ = new QLineEdit(ctrlGroup_);
    vLay->addWidget(leB1_);
    vLay->addWidget(leB2_);

    // 按钮
    vLay->addSpacing(20);
    btnSolve_ = new QPushButton(tr("求 解"), ctrlGroup_);
    btnReset_ = new QPushButton(tr("重 置"), ctrlGroup_);
    vLay->addWidget(btnSolve_);
    vLay->addWidget(btnReset_);
    vLay->addStretch();
    ctrlGroup_->setLayout(vLay);

    // 右侧：渲染区
    render_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    // 布局比例：控制面板 1，渲染区 3
    mainLay->addWidget(ctrlGroup_, 1);
    mainLay->addWidget(render_, 3);
    setLayout(mainLay);

    // 信号槽
    connect(btnSolve_, &QPushButton::clicked, this, &LinearEquationWindow::onSolveClicked);
    connect(btnReset_, &QPushButton::clicked, this, &LinearEquationWindow::onResetClicked);
}

void LinearEquationWindow::onSolveClicked() {
    // 读取 A 和 b
    Eigen::Matrix2f A;
    A << leA11_->text().toFloat(), leA12_->text().toFloat(),
        leA21_->text().toFloat(), leA22_->text().toFloat();
    Eigen::Vector2f b(leB1_->text().toFloat(), leB2_->text().toFloat());

    // 检查可逆性
    if (std::abs(A.determinant()) < 1e-6f) {
        QMessageBox::warning(this, tr("无法求解"), tr("矩阵 A 不可逆，无法求解。"));
        return;
    }

    // 求解 x = A^{-1} b
    Eigen::Vector2f x = A.fullPivLu().solve(b);

    // 可视化
    render_->showSolution({ x.x(), x.y() });
}

void LinearEquationWindow::onResetClicked() {
    render_->resetView();
    render_->clearSolution();
}
